﻿using ThingsEdge.Contracts;
using ThingsEdge.Contracts.Variables;
using ThingsEdge.Router.Interfaces;

namespace Digitalmes.Infrastructure.Scada.Handlers;

/// <summary>
/// SCADA 请求预处理事件
/// </summary>
internal sealed class DirectApiHandler : IDirectMessageRequestApi
{
    private readonly IServiceProvider _serviceProvider;

    public DirectApiHandler(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public async Task PostAsync(PayloadData? lastMasterPayloadData, RequestMessage requestMessage, CancellationToken cancellationToken)
    {
        if (requestMessage.Flag != TagFlag.Notice)
        {
            return;
        }

        var self = requestMessage.Self();
        IReciveMessageHandler? recivedHandler = self.TagName switch
        {
            string name when name.StartsWith(LedGuideRecivedHandler.PrefixKey) 
                => _serviceProvider.GetKeyedService<IReciveMessageHandler>(nameof(LedGuideRecivedHandler)),
            _ => null,
        };

        if (recivedHandler != null)
        {
            await recivedHandler.ReciveAsync(requestMessage, cancellationToken);
        }
    }
}
